package com.springboot.personblogsystem.interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.nio.charset.StandardCharsets;

import static com.springboot.personblogsystem.common.Constants.USERINFO;

/**
 * Created with IntelliJ IDEA.
 * Description :
 * User: jiume
 * Date: 2025-05-14
 * Time: 17:05
 */
@Slf4j
@Component
public class UserLoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 校验用户是否登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute(USERINFO) == null) {
            log.info("用户未登录");
            response.setStatus(401); // 未登录
            response.setContentType("text/html;charset=UTF-8");
            response.getOutputStream().write("用户未登录".getBytes(StandardCharsets.UTF_8));
            return false;
        }
        return true;
    }
}
